import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Calendar;
import java.util.TimerTask;
import java.util.Timer;

/*
 * Description:Timer类演示示例
 * Timer类用于创建任务，同时可以调用schedule方法进行任务的调度
 * cancel方法可以实现任务的终止
 * Author: AMark
 * Date:11/16/2023
 * Time:11:04 PM
 */
class WatchGUI {
    JFrame frame = null;
    JLabel jLabel = null;
    public WatchGUI(String s) {
        frame = new JFrame(s);
        jLabel = new JLabel("",JLabel.CENTER);
        //通过匿名类创建对象事件处理器
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//新建任务类
class MyTask extends TimerTask {
    String string;
    WatchGUI wg;
    public MyTask(WatchGUI wg) {
        this.wg = wg;
    }
    public void run() {
        //设置任务为显示系统时间
        Calendar calendar = Calendar.getInstance();
        string = new String(calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND));
        wg.jLabel.setText(string);
        wg.frame.add(wg.jLabel);
        wg.frame.setSize(180, 70);
        wg.frame.setVisible(true);
    }

}

public class TimerDemo {
    public static void main(String[] args) throws InterruptedException{
        Timer timer = new Timer();
        WatchGUI wg = new WatchGUI("Watch");
        MyTask myTask = new MyTask(wg);
        timer.schedule(myTask, 0, 1000);
    }
}
